import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'


let camera, controls
let renderer
let scene 

initRenderer()
initScene()
initAxesHelper()
initCamera()
initControls()

init()
animate()
window.addEventListener('resize', onWindowResize)

function initRenderer(params) {
    renderer = new THREE.WebGLRenderer({ antialias: true })
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    document.body.appendChild(renderer.domElement)
}

function initScene(params) {
    scene = new THREE.Scene()
}

function initAxesHelper(params) {
    scene.add(new THREE.AxesHelper(50))
}

function initCamera(params) {
    camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight)
    camera.position.set(0.2,0,0.2)
}

function initControls(params) {
    controls = new OrbitControls(camera, renderer.domElement)
    controls.enableZoom = false
    controls.enableDamping = true
    // controls.enablePan
    // controls.rotateSpeed = -0.25

}

function init(params) {

    const textures = getTexturesFromAtlasFile(
        'textures/cube/sun_temple_stripe.jpg',6
    );
    const materials = []
    for (let i = 0; i < textures.length; i++) { 
        materials.push(
            new THREE.MeshBasicMaterial({
                    map:textures[i]
                })
            )
    }

    const geometry = new THREE.BoxGeometry(1, 1, 1)
    // const material = new THREE.MeshBasicMaterial()
    const skyBox = new THREE.Mesh(geometry, materials)
    skyBox.geometry.scale(1,1,-1)
    scene.add(skyBox)
}

function getTexturesFromAtlasFile(file,tilesNum) {
    const textures = []
    for (let i = 0; i < tilesNum; i++) {
         textures[i] = new THREE.Texture()
    }
    new THREE.ImageLoader().load(
        file,
        function (image) {
            console.log(image);
            const width = image.height;
            let canvas, context
            for (let i = 0; i < tilesNum; i++) {
                canvas = document.createElement('canvas');
                context = canvas.getContext('2d');
                canvas.height = width;
                canvas.width = width;
                context.drawImage(image, width * i, 0, width, width, 0,0, width, width);
                textures[i].image = canvas;
                textures[i].needsUpdate = true;
            }

        }
    );
    return textures
}

function onWindowResize(params) {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth,window.innerHeight);
}

function animate(params) {
    requestAnimationFrame(animate)
    controls.update() // required when damping is enabled
    renderer.render(scene,camera)
}